<template>
  <div class="warning-event-list">
    <a-card title="预警事件列表">
      <a-form layout="inline">
        <a-form-item label="">
          <a-select
            v-model="queryParam.modelUuid"
            placeholder="请选择模型类型"
            :style="{
              width: '200px',
            }"
            @change="onModelChange">
            <a-select-option v-for="model in modelList" :key="model.uuid" :value="model.uuid">
              {{ model.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="">
          <a-select
            v-model="queryParam.version"
            placeholder="请选择模型版本"
            :style="{
              width: '200px',
            }">
            <a-select-option v-for="version in versionList" :key="version.id" :value="version.version">
              {{ version.version }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="">
          <a-date-picker
            v-model="queryParam.startTime"
            placeholder="开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            show-time
            :style="{
              width: '200px',
            }" />
        </a-form-item>
        <a-form-item label="">
          <a-date-picker
            v-model="queryParam.endTime"
            placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            show-time
            :style="{
              width: '200px',
            }" />
        </a-form-item>
        <a-form-item label="">
          <a-button type="primary" @click="searchHandle">搜索</a-button>
        </a-form-item>
      </a-form>
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="false"
        :scroll="{ x: 1200 }"
        showPagination="auto">
        <template slot="modelName" slot-scope="text, record">
          <a-tooltip>
            <template slot="title">{{ record.name }}</template>
            {{ record.name }}
          </a-tooltip>
        </template>
        <template slot="content" slot-scope="text, record">
          <div v-html="formatContent(text)"></div>
        </template>
        <template slot="status" slot-scope="text, record">
          <span :class="getStatusClass(record.status)">
            {{ getStatusText(record.status) }}
          </span>
        </template>
        <!-- <template slot="sent" slot-scope="text, record">
        <a-tag :color="record.sent ? 'success' : 'default'">
          {{ record.sent ? '已送达' : '未送达' }}
        </a-tag>
      </template> -->
        <span slot="operation" slot-scope="text, record">
          <a-button type="link" @click="handleDetail(record)" v-if="$hasPermission('alertConfig')">查看配置</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="handleDelete(record)" v-if="$hasPermission('deleteAlert')">删除</a-button>
        </span>
      </s-table>

      <!-- 预警配置弹窗 -->
      <configure-drawer
        :visible="configureVisible"
        :record="selectedRecord"
        @close="handleConfigureClose"
        @confirm="handleConfigureConfirm" />
    </a-card>
  </div>
</template>

<script>
import Vue from 'vue'
import { STable } from '@/components'
import ConfigureDrawer from '@/components/WarnConfigure/index.vue'
import { alert, allModel, alertDelete } from '@/api/warningEvent'
import moment from 'moment'
const columns = [
  {
    title: '模型名称',
    dataIndex: 'name',
    width: 120,
    scopedSlots: { customRender: 'modelName' },
  },
  {
    title: '模型版本',
    dataIndex: 'version',
    width: 100,
  },
  {
    title: '预警详情',
    dataIndex: 'content',
    width: 250,
    scopedSlots: { customRender: 'content' },
  },
  {
    title: '预警时间',
    dataIndex: 'time',
    width: 180,
    customRender: (text, record) => {
      return moment(text).format('YYYY-MM-DD HH:mm:ss')
    },
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 120,
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    scopedSlots: { customRender: 'status' },
  },
  // {
  //   title: '送达状态',
  //   dataIndex: 'sent',
  //   width: 100,
  //   scopedSlots: { customRender: 'sent' },
  // },
  {
    title: '操作',
    scopedSlots: { customRender: 'operation' },
    width: 220,
    fixed: 'right',
  },
]
export default {
  name: 'WarningEventList',
  components: {
    STable,
    ConfigureDrawer,
  },
  beforeRouteEnter(to, from, next) {
    if (from.path === '/403') {
      window.location.reload()
      return
    }
    next((vm) => {
      if (!vm.$hasPermission('queryAlert')) {
        vm.$router.push({ path: '/403' })
      }
    })
  },
  props: {},
  data() {
    const now = moment()
    const sevenDaysAgo = moment().subtract(7, 'days')

    return {
      columns,

      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      queryParam: {
        modelUuid: undefined,
        version: undefined,
        startTime: sevenDaysAgo,
        endTime: now,
      },
      modelList: [],
      versionList: [],
      selectedModel: null,
      configureVisible: false,
      selectedRecord: {},
    }
  },
  mounted() {
    this.initFromUrlParams()
    this.loadModelList()
    // 如果有URL参数，在初始化完成后刷新表格数据
    if (this.$route.query.modelUuid || this.$route.query.version) {
      this.$nextTick(() => {
        this.$refs.table && this.$refs.table.refresh(true)
      })
    }
  },
  methods: {
    handleTableChange(pagination) {
      this.$emit('change', pagination)
    },
    searchHandle() {
      this.$refs.table.refresh(true)
    },
    loadData(parameter) {
      // 处理时间范围
      let startTime = ''
      let endTime = ''
      if (this.queryParam.startTime) {
        startTime = this.queryParam.startTime.valueOf().toString()
      }

      if (this.queryParam.endTime) {
        endTime = this.queryParam.endTime.valueOf().toString()
      }

      const requestParameters = Object.assign(
        {},
        {
          curPage: parameter.pageNo || 1,
          pageSize: parameter.pageSize || 10,
          startTime: startTime,
          endTime: endTime,
          modelUuid: this.queryParam.modelUuid || '',
          version: this.queryParam.version || '',
        }
      )

      console.log('loadData request parameters:', requestParameters)
      return alert(requestParameters).then((res) => {
        if (res.success && res.data) {
          return {
            ...res.data,
            data: res.data.modelData || [],
          }
        }
        return {
          total: 0,
          curPage: 1,
          data: [],
          totalPage: 0,
          pageSize: 10,
        }
      })
    },
    handleDetail(record) {
      this.selectedRecord = record
      this.configureVisible = true
    },
    handleConfigureClose() {
      this.configureVisible = false
      this.selectedRecord = {}
    },
    handleConfigureConfirm(data) {
      console.log('预警配置数据:', data)
      // 这里可以调用API保存配置
    },
    handleDelete(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除预警"${record.name}"吗？`,
        onOk: () => {
          alertDelete({ id: record.id })
            .then((res) => {
              if (res.success || res.code === 200) {
                this.$message.success('删除成功')
                this.$refs.table.refresh()
              } else {
                this.$message.error(res.message || '删除失败')
              }
            })
            .catch((error) => {
              console.error('删除预警失败:', error)
              this.$message.error('删除失败，请稍后重试')
            })
        },
      })
    },
    formatContent(text) {
      try {
        const contentArray = JSON.parse(text)
        if (Array.isArray(contentArray) && contentArray.length > 0) {
          const formattedItems = contentArray.map(item => {
            const typeMap = {
              'compareB': 'PSI跟建模对比',
              'compareD': 'PSI跟昨天对比',
              'compareW': 'PSI跟上周对比',
              'compareM': 'PSI跟上月对比',
              'modelCallD': '调用量天对比',
              'modelCallH': '调用量小时对比',
              'AUC': 'AUC',
              'KS': 'KS'
            }
            const typeName = typeMap[item.type] || item.type
            const compareText = item.compareKey === '>' ? '>'
                              : item.compareKey === '<' ? '<'
                              : item.compareKey === '=' ? '='
                              : item.compareKey === '>=' ? '>='
                              : item.compareKey === '<=' ? '<=' : item.compareKey

            // 格式化实际值，整数显示整数，小数保留两位
            let actualValue = item.val
            if (typeof item.val === 'number') {
              if (Number.isInteger(item.val)) {
                actualValue = item.val.toString()
              } else {
                actualValue = item.val.toFixed(2)
              }
            }

            return `<div style="margin-bottom: 4px; font-size: 13px;">
              <span style="color: #333;">${typeName}</span>
              <span style="margin: 0 4px; color: #666;">${compareText}</span>
              <span style="color: #1890ff;">${item.threshold}</span>
              <span style="margin-left: 8px; color: #999;">(实际: </span>
              <span style="color: #f5222d;">${actualValue}</span>
              <span style="color: #999;">)</span>
            </div>`
          })
          return `<div style="line-height: 1.3;">${formattedItems.join('')}</div>`
        }
        return text
      } catch (error) {
        return text
      }
    },
    getStatusText(status) {
      const statusMap = {
        0: '未读',
        1: '已读',
      }
      return statusMap[status] || '未知状态'
    },
    getStatusClass(status) {
      const classMap = {
        0: 'status-unread',
        1: 'status-read',
      }
      return classMap[status] || 'status-unknown'
    },
    // 从URL参数初始化筛选条件
    initFromUrlParams() {
      const { modelUuid, version } = this.$route.query

      if (modelUuid) {
        this.queryParam.modelUuid = modelUuid
      }

      if (version) {
        this.queryParam.version = version
      }

      // 如果有URL参数，需要在模型列表加载完成后更新版本列表
      if (modelUuid) {
        this.$nextTick(() => {
          this.updateVersionList()
        })
      }
    },
    loadModelList() {
      allModel({ monitor: 1 })
        .then((res) => {
          if (res.code === 200 && res.data) {
            this.modelList = res.data
            // 如果已选择模型类型，更新版本列表
            this.updateVersionList()
            // 如果有URL参数中的modelUuid，确保版本列表正确更新
            if (this.queryParam.modelUuid) {
              this.updateVersionList()
            }
          }
        })
        .catch((error) => {
          console.error('获取模型列表失败:', error)
        })
    },
    onModelChange(value) {
      // 模型类型改变时，清空版本选择并更新版本列表
      this.queryParam.version = ''
      this.updateVersionList()
    },
    onVersionChange(value) {
      // 版本改变时的处理逻辑
      console.log('版本已改变:', value)
    },
    updateVersionList() {
      // 根据选择的模型类型更新版本列表
      if (this.queryParam.modelUuid) {
        const selectedModel = this.modelList.find((model) => model.uuid === this.queryParam.modelUuid)
        if (selectedModel && selectedModel.version) {
          // 解析版本字符串，支持单个版本(V1)或多个版本(V1,V2)格式
          const versions = selectedModel.version.split(',').map((v) => v.trim())
          this.versionList = versions.map((version, index) => ({
            id: `${selectedModel.id}_${index}`,
            version: version,
            name: version,
          }))
          // 自动选中第一条版本数据
          if (this.versionList.length > 0) {
            this.queryParam.version = this.versionList[0].version
          }
        } else {
          this.versionList = []
        }
      } else {
        // 如果没有选择模型类型，版本列表为空
        this.versionList = []
      }
    },
  }
}
</script>

<style lang="less" scoped>
.warning-event-list {

  .ant-form {
    margin-bottom: 20px;
    padding: 20px;
    background: #fafafa;
    border-radius: 6px;
  }

  :deep(.ant-table-thead > tr > th) {
    background: #fafafa;
    font-weight: 600;
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background: #f5f5f5;
  }

  .status-unread {
    display: inline-flex;
    align-items: center;
    padding: 4px 12px;
    background: linear-gradient(135deg, #fff1f0 0%, #ffebe8 100%);
    border: 1px solid #ffccc7;
    border-radius: 16px;
    color: #cf1322;
    font-weight: 500;
    font-size: 12px;
    letter-spacing: 0.5px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 2px 4px rgba(255, 77, 79, 0.1);

    &::before {
      content: '';
      width: 6px;
      height: 6px;
      background: #ff4d4f;
      border-radius: 50%;
      margin-right: 6px;
      box-shadow: 0 0 6px rgba(255, 77, 79, 0.4);
      animation: pulse-red 2s infinite;
    }

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(255, 77, 79, 0.2);
      border-color: #ff7875;
    }
  }

  .status-read {
    display: inline-flex;
    align-items: center;
    padding: 4px 12px;
    background: linear-gradient(135deg, #f6ffed 0%, #efffb8 100%);
    border: 1px solid #b7eb8f;
    border-radius: 16px;
    color: #389e0d;
    font-weight: 500;
    font-size: 12px;
    letter-spacing: 0.5px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 2px 4px rgba(82, 196, 26, 0.1);

    &::before {
      content: '✓';
      width: 14px;
      height: 14px;
      background: #52c41a;
      border-radius: 50%;
      margin-right: 6px;
      color: white;
      font-size: 10px;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: center;
      line-height: 1;
    }

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(82, 196, 26, 0.2);
      border-color: #73d13d;
    }
  }

  .status-unknown {
    display: inline-flex;
    align-items: center;
    padding: 4px 12px;
    background: linear-gradient(135deg, #fafafa 0%, #f0f0f0 100%);
    border: 1px solid #d9d9d9;
    border-radius: 16px;
    color: #8c8c8c;
    font-weight: 500;
    font-size: 12px;
    letter-spacing: 0.5px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &::before {
      content: '?';
      width: 14px;
      height: 14px;
      background: #bfbfbf;
      border-radius: 50%;
      margin-right: 6px;
      color: white;
      font-size: 10px;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: center;
      line-height: 1;
    }
  }

  @keyframes pulse-red {
    0% {
      box-shadow: 0 0 6px rgba(255, 77, 79, 0.4);
    }

    50% {
      box-shadow: 0 0 12px rgba(255, 77, 79, 0.8);
    }

    100% {
      box-shadow: 0 0 6px rgba(255, 77, 79, 0.4);
    }
  }
}
</style>
